/**
 * Created by zhangsong on 2019-05-08.
 */
import PDFPreview from '@/components/PDFPreview';
import ReaderCard from '@/components/ReaderCard/staffIndex';
import ReaderCardIc from '@/components/ReaderCard/staffIndexIc';
import Power from '@/constants/power';
import Authorized from '@/utils/Authorized';
import React, { Component, Fragment } from 'react';
import { Button, Popconfirm, Table, Modal, DatePicker, Icon } from 'antd';
import { connect } from 'dva';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { formatMessage } from '@/utils/i18n';
import StaffReducer from '@/dva/application/staff';
import { Pagination } from '@/constants/styleConfig';
import { StaffApplication } from '@/constants/routes';
import Search from './search';
import moment from 'moment';
import _ from 'lodash';

const { Namespace, Effects } = StaffReducer;
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/c/font_3604216_kag2bfyte9s.js',
});

@connect(
  state => ({
    staffStore: state[Namespace],
  }),
  dispatch => ({
    handleQuery: data =>
      dispatch({
        type: `${Namespace}/${Effects.listByParam}`,
        data,
      }),
    removeById: data =>
      dispatch({
        type: `${Namespace}/${Effects.removeById}`,
        data,
      }),
    getPreviewPdfById: id =>
      dispatch({
        type: `${Namespace}/${Effects.getPreviewPdfById}`,
        data: {
          id,
        },
      }),
    handPDFModalCancel: () =>
      dispatch({
        type: `${Namespace}/${Effects.handPDFModalCancel}`,
        data: {},
      }),
    downLoadXlsx: () =>
      dispatch({
        type: `${Namespace}/${Effects.downLoadXlsx}`,
        data: {},
      }),
    openCallModal: data =>
      dispatch({
        type: `${Namespace}/${Effects.openCallModal}`,
        data,
      }),
    updateCallDate: data =>
      dispatch({
        type: `${Namespace}/${Effects.updateCallDate}`,
        data,
      }),
  }),
)
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      readerCardModal: false,
      record: null,
      calldate: undefined,
      messdate: null,
      readerIcCardModal: false,
      newdata: new Date(new Date().getTime() - 24 * 60 * 60 * 1000),
      exloading: false,
    };
  }

  componentDidMount() {
    const { handleQuery } = this.props;
    handleQuery({});
  }

  onDetailClick = (text, record) => {
    const { history } = this.props;
    const { id } = record;
    history.push(`${StaffApplication.detail.url}?id=${id}`);
  };

  handleUpdate = (text, record) => {
    const { history } = this.props;
    const { id } = record;
    history.push(`${StaffApplication.modify.url}?id=${id}`);
  };

  onDownload = listData => {
    // downloadCsv()
    // const array = listData.map(({ surname, nameAlias }) => [surname, nameAlias])
    // downloadCsv(array, ['name', 'age'], 'test.xlsx');
    const { downLoadXlsx } = this.props;
    downLoadXlsx();
    console.log('guolaiaiuiaia', Namespace, Effects, listData);
  };

  onPreviewClick = (text, record) => {
    const { getPreviewPdfById } = this.props;
    const { id } = record;
    getPreviewPdfById(id);
  };

  onPreviewClickSure = () => {
    const { handPDFModalCancel } = this.props;
    handPDFModalCancel();
  };

  handleDelete = (text, record) => {
    const { staffStore, removeById } = this.props;
    removeById({
      id: record.id,
      page: staffStore.page,
      pageSize: staffStore.pageSize,
      query: staffStore.query,
    });
  };

  openRegisterEface = record => {
    this.setState({
      readerCardModal: true,
      record,
    });
  };

  openRegisterEfaceIc = record => {
    this.setState({
      readerIcCardModal: true,
      record,
    });
  };

  openCancellAtion = item => {
    console.log('openCancellAtion', item, item.checked_expiry);
    const { openCallModal } = this.props;
    this.setState({
      calldate: item.expire_date,
      messdate: item,
      newdata: new Date(new Date().getTime() - 24 * 60 * 60 * 1000),
    })
    openCallModal(true);
  }

  renderColumns = () => [
    {
      title: formatMessage('applicationContractor.columns.headPhoto.name'),
      key: 'photograph_url',
      render: (text, record, index) => {
        return (
          <div>
            <img
              alt={formatMessage(
                'applicationContractor.columns.headPhoto.name',
              )}
              src={
                record.headPhoto
              }
              width={104}
              height={104}
            />
          </div>
        );
      },
    },
    {
      title: formatMessage('applicationStaff.columns.surname.name'),
      dataIndex: 'surname',
    },
    {
      title: formatMessage('applicationContractor.columns.nameAlias.name'),
      dataIndex: 'alias',
    },
    {
      title: formatMessage('applicationStaff.columns.staffNo.name'),
      dataIndex: 'staffNo',
    },
    {
      title: formatMessage('applicationStaff.columns.position.name'),
      dataIndex: 'position',
    },
    {
      title: formatMessage('applicationStaff.columns.division.name'),
      dataIndex: 'division',
    },
    {
      title: formatMessage('applicationStaff.columns.department.name'),
      dataIndex: 'department',
    },
    {
      title: formatMessage('applicationStaff.columns.zoneSpecified.name'),
      dataIndex: 'zoneSpecified',
    },
    {
      title: formatMessage('applicationStaff.columns.passNumber.name'),
      dataIndex: 'passNumber',
    },
    {
      title: formatMessage('baseInfo.approvalStatusName'),
      dataIndex: 'status',
      render: text => {
        if (text === 1) {
          return formatMessage('baseInfo.approvalStatus');
        }
        if (text === -1) {
          return formatMessage('baseInfo.disapprovalStatus');
        }
        if (text === 0) {
          return formatMessage('baseInfo.needApprovalStatus');
        }
        if (text === 3) {
          return formatMessage('applicationContractor.temporary.cancelled');
        }
        return null;
      },
    },
    {
      title: formatMessage('applicationCommon.readerCard.passno'),
      dataIndex: 'card_no',
    },
    {
      title: formatMessage('baseInfo.updateTime'),
      dataIndex: 'updateTime',
    },
    {
      title: formatMessage('button.operator'),
      key: 'operator',
      render: (text, record, index) => {
        const onUpdateClick = () => {
          this.handleUpdate(text, record, index);
        };
        const onDeleteClick = () => {
          this.handleDelete(text, record, index);
        };
        const onDetailClick = () => {
          this.onDetailClick(text, record, index);
        };
        const onPreviewClick = () => {
          this.onPreviewClick(text, record, index);
        };
        return (
          <div>
            <Button
              className="recovery"
              htmlType="button"
              size="small"
              onClick={onDetailClick}
              icon="eye"
            />
            <Authorized authority={Power.StaffApplication.printing}>
              <Button
                htmlType="button"
                type="dashed"
                size="small"
                onClick={() => this.openRegisterEface(record)}
              >
                {formatMessage('applicationCommon.readerCard.buttonName')}
              </Button>
            </Authorized>
            <Authorized authority={Power.StaffApplication.modify}>
              <Button
                className="recovery"
                htmlType="button"
                type="dashed"
                size="small"
                onClick={onUpdateClick}
                icon="edit"
              />
            </Authorized>
            {record.status === 0 ? (
              <Fragment>
                <Authorized authority={Power.StaffApplication.remove}>
                  <Popconfirm
                    title={formatMessage({ id: 'baseInfo.askDeleteRecord' })}
                    onConfirm={onDeleteClick}
                    okText={formatMessage({ id: 'button.sure' })}
                    cancelText={formatMessage({ id: 'button.cancel' })}
                  >
                    <Button type="danger" size="small" icon="delete" />
                  </Popconfirm>
                </Authorized>
              </Fragment>
            ) : null}
            <Authorized authority={Power.StaffApplication.preview}>
              <Button htmlType="button" size="small" onClick={onPreviewClick} icon="file-pdf" />
            </Authorized>
            <Authorized authority={Power.StaffApplication.cancellation}>
              <Button
                htmlType="button"
                type="dashed"
                size="small"
                onClick={() => this.openCancellAtion(record)}
              >
                {formatMessage('applicationCommon.readerCard.cancellAtion')}
              </Button>
            </Authorized>
            <Authorized authority={Power.StaffApplication.modifyic}>
              <Button
                htmlType="button"
                type="dashed"
                size="small"
                onClick={() => this.openRegisterEfaceIc(record)}
              >
                <IconFont type="icon-nfc" />
              </Button>
              {/* <Button
                className="recovery"
                htmlType="button"
                type="dashed"
                size="small"
                onClick={onUpdateClick}
                icon="material-design-icons"
              /> */}
            </Authorized>
          </div>
        );
      },
    },
  ];

  closeRegisterEface = () => {
    this.setState({
      readerCardModal: false,
      record: null,
      readerIcCardModal: false,
    });
  };

  submitRegisterCard = () => {
    const { handleQuery } = this.props;
    this.setState({
      readerCardModal: false,
      record: null,
      readerIcCardModal: false,
    });
    handleQuery();
  };

  onChange = pagination => {
    const { current, pageSize } = pagination;
    const { handleQuery, staffStore } = this.props;
    const { query } = staffStore;
    handleQuery({
      query,
      page: current,
      pageSize,
    });
  };

  onOkDate = () => {
    console.log('看看這個時間11', this.state.newdata);
    if (!this.state.newdata) {
      return
    }
    const { messdate, newdata } = this.state;
    const { updateCallDate, staffStore } = this.props;
    const data = {
      update: {
        surname: _.get(messdate, 'surname', null),
        id: messdate.id,
        pass_numbered: _.get(messdate, 'pass_numbered', null),
        expire_date: newdata,
      },
      pagesize: {
        page: staffStore.page,
        pageSize: staffStore.pageSize,
      },
    }
    console.log('看看這個時間', messdate, newdata, moment(newdata));
    updateCallDate(data)
  }

  onCallDate = (date, dateString) => {
    console.log('date, dateString', date, dateString);
    this.setState({
      newdata: dateString == null ? undefined : dateString,
    })
  }

  render() {
    const { staffStore = {}, openCallModal } = this.props;
    const {
      pageSize,
      page,
      listData,
      total,
      listLoading,
      pdfLoading,
      pdfReview,
      pdfPreviewVisible,
      callMadal,
      xslloading,
    } = staffStore;
    const { readerCardModal, record, calldate, readerIcCardModal, newdata } = this.state;
    const defvalue = newdata ? moment(newdata, 'YYYY-MM-DD') : undefined;
    const newdefvalue = calldate ? moment(calldate).format('YYYY-MM-DD') : undefined;
    const pagination = Pagination({
      page,
      pageSize,
      total,
    });
    console.log('staffStorestaffStore', this.props)
    return (
      <PageHeaderWrapper>
        <Search exloading={xslloading} onDownload={() => this.onDownload(listData)} />
        <Modal
          title={formatMessage('applicationCommon.readerCard.cancellAtion')}
          visible={callMadal}
          onCancel={() => {
            openCallModal(false);
          }}
          onOk={this.onOkDate}
        >
          <div>
            <div style={{ marginBottom: '10px' }}>
              <span style={{ marginRight: 10 }}>{`${formatMessage('applicationCommon.readerCard.donecancellAtionDate')}:`}</span>
              <span style={{ marginRight: 10 }}>{`${newdefvalue}`}</span>
            </div>
            <span style={{ marginRight: 10 }}>{`${formatMessage('applicationCommon.readerCard.modifycancellAtionDate')}:`}</span>
            <DatePicker value={defvalue} onChange={this.onCallDate} />
            {
              !calldate ? (
                <span style={{ marginLeft: 10, color: 'red' }}>請選擇</span>
              ) : null
            }

          </div>
        </Modal>
        {readerCardModal ? (
          <ReaderCard
            record={record}
            cancel={this.closeRegisterEface}
            sure={this.submitRegisterCard}
          />
        ) : null}

        {
          readerIcCardModal ? (
            <ReaderCardIc
              record={record}
              cancel={this.closeRegisterEface}
              sure={this.submitRegisterCard}
            />
          ) : null
        }
        <Table
          loading={!!listLoading}
          rowKey="id"
          columns={this.renderColumns()}
          dataSource={listData}
          onChange={this.onChange}
          pagination={pagination}
        />
        <PDFPreview
          visible={pdfPreviewVisible}
          url={pdfReview}
          loading={pdfLoading}
          printing={Authorized.check(Power.StaffApplication.printing, true, false)}
          onOk={() => this.onPreviewClickSure()}
        />
      </PageHeaderWrapper>
    );
  }
}

export default Index;
